package com.haust.leyou.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.domain.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Auther: csp1999
 * @Date: 2020/12/09/15:17
 * @Description:
 */
@Service
public class UploadService {

    private static final List<String> CONTENT_TPYES =
            Arrays.asList("image/gif", "image/png", "image/jpeg");

    private static final Logger logger = LoggerFactory.getLogger(UploadService.class);

    // fastDFS 存储客户端
    @Autowired
    private FastFileStorageClient storageClient;

    // 用于获取 fastDFS 图片缩略图
    @Autowired
    private ThumbImageConfig thumbImageConfig;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    public String uploadImage(MultipartFile file) {

        String originalFilename = file.getOriginalFilename();// 原文件名称
//        String last = StringUtils.substringAfterLast(originalFilename, ".");
//        System.out.println(last);

        // 1.校验文件类型(根据后缀校验类型)
        String contentType = file.getContentType();
//        System.out.println(CONTENT_TPYES);
//        System.out.println(CONTENT_TPYES.contains(contentType));
//        System.out.println(contentType);
        if (!CONTENT_TPYES.contains(contentType)) {
            logger.info("文件类型不合法：{}", originalFilename);
            return null;
        }

        try {
            // 2.校验文件内容(校验文件！内容！是否是图片)
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                logger.info("文件内容不是图片：{}", originalFilename);
                return null;
            }

            // 3.保存到服务器(本地上传)
//            file.transferTo(new File("M:\\code\\IDEA\\leyou\\image\\" + originalFilename));
            // 3.文件保存到服务器(FastDFS上传)
            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            /**
             * 上传并保存图片
             *
             * 参数：
             * 1-上传的文件流
             * 2-文件的大小
             * 3-文件的后缀
             * 4-可以不管他
             */
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);

            // 4.返回文件的url,给前端进行回显！
//            return "http://image.leyou.com/image/" + originalFilename;
            return "http://image.csp1999.top/" + storePath.getFullPath();

        } catch (IOException e) {
            logger.info("服务器内容错误：{}" + originalFilename);
            e.printStackTrace();
        }

        return null;
    }
}
